import { defineStore } from "pinia";
import axios from "axios";
import { nanoid } from "nanoid";
import { reactive } from "vue";

// export const useTalkStore = defineStore("talk", {
//   state() {
//     // 真正存储数据的地方
//     return {
//       talkList: JSON.parse(localStorage.getItem("talkList") as string) || [],
//     };
//   },
//   actions: {
//     async getTalk() {
//       // // 发请求,连续解构赋值 + 重命名
//       let {
//         data: { content },
//       } = await axios.get("https://api.uomg.com/api/rand.qinghua?format=json");
//       // // 把请求回来的字符串,包装成一个对象
//       let obj = { id: nanoid(), content };
//       this.talkList.unshift(obj);
//     },
//   },
// });

export const useTalkStore = defineStore("talk", () => {
  // talkList 就是 state
  const talkList = reactive(
    JSON.parse(localStorage.getItem("talkList") as string) || []
  );
  // getTalk 函数相当于 action
  async function getTalk() {
    // // 发请求,连续解构赋值 + 重命名
    let {
      data: { content },
    } = await axios.get("https://api.uomg.com/api/rand.qinghua?format=json");
    // // 把请求回来的字符串,包装成一个对象
    let obj = { id: nanoid(), content };
    talkList.unshift(obj);
  }
  return { talkList, getTalk }
});
